#!/bin/bash
###
 # 该脚本只针对 Ubuntu 1604和1804 提供一键换源任务
 # 可更换的源有
 # 1. aliyun(阿里云)
 # 2. tsinghua(清华)
 # 3. ustc(中科大)
###

perr() {
    printf "\033[31m $1 \033[0m \n"
}
psuc() {
    printf "\033[32m $1 \033[0m \n"
}

name=`echo $*`
[ -z $name ] && name=tsinghua

# 1. 解析参数
if [ `echo $name | grep -q aliyun && echo 0` ]; then
    name=aliyun
    url="http:\/\/mirrors.aliyun.com\/ubuntu\/"
elif [ `echo $name | grep -q tsinghua && echo 0` ];then
    name=tsinghua
    url="https:\/\/mirrors.tuna.tsinghua.edu.cn\/ubuntu\/"
elif [ `echo $name | grep -q ustc && echo 0` ];then
    name=ustc
    url="https:\/\/mirrors.ustc.edu.cn\/ubuntu\/"
else
    perr "源名称有误，当前只支持aliyun、tsinghua、ustc" && exit
fi

psuc "当前设置源为： $name 源！"

# 2. 检测当前系统版本
cat /etc/issue | grep -q 16.04 && version=xenial
cat /etc/issue | grep -q 18.04 && version=bionic
# 2.1 判断 version 里面是否有值
[ -z $version ] && perr "当前系统为不支持的版本..." && exit


filename=/tmp/sources.list
# 3. 将源文件写入 tmp 目录
wget -O $filename https://gitee.com/askeynil/AskConfiguration/raw/master/sources.list
# 3.1 判断 sources 是否下载成功
if [ -d $filename ]; then
    perr "sources.list 不存在,请重试..."
    exit
fi
# 3.2 更换源中代码
sed -i "s/__url__/$url/g" $filename
sed -i "s/__version__/$version/g" $filename

# 4. 比较两个源文件是否一致
diff -qB $filename /etc/apt/sources.list
if [ $? != 0 ];then
    perr "当前源不一致 执行替换源操作"
    # ?两个文件不一样
    # 给原来的源文件做一个备份
    sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
    # 将当前的源拷贝到该目录
    sudo mv $filename /etc/apt/sources.list
else
    perr "当前源和更换的源一致，无需更换"
fi

# 5. 删除下载的源文件
rm -rf $filename

# 6. 更新源
sudo rm -f /var/lib/apt/lists/lock
sudo apt update
